package com.world.rickcloudendpoint.demo.local;

import com.world.rickcloudendpoint.common.exception.QueueException;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.AbstractQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @description: 本地队列工厂
 * @author: jlsong
 * @date: 2022/06/03 20:05:16
 * @version: 1.0
 */
@Log4j2
public class LocalQueueFactory {

    private final ConcurrentHashMap<String, AbstractQueue> queueHolders = new ConcurrentHashMap<>();

    public static LocalQueueFactory getInstance() {
        return LocalQueueFactory.QueueFactoryHolder.INSTANCE;
    }

    private static class QueueFactoryHolder {
        private static final LocalQueueFactory INSTANCE = new LocalQueueFactory();
    }

    public void addQueue(String queueName){
        AbstractQueue queue = queueHolders.get(queueName);
        if (queue == null){
            queueHolders.putIfAbsent(queueName, new LinkedBlockingQueue());
            return;
        }
        log.warn("queue name [{}] 已存在");
    }


    /**
     * 获取队列实例
     * if(init){
     * return instance;
     * }elseP{
     * create queue instance;
     * return instance;
     * }
     *
     * @param queueName 队列名称
     * @return
     * @throws QueueException
     */
    public AbstractQueue getQueue(String queueName) throws QueueException {

        try {
            AbstractQueue queueHolder = queueHolders.get(queueName);
            if (queueHolder == null) {
                queueHolders.putIfAbsent(queueName, new LinkedBlockingQueue());
                queueHolder = queueHolders.get(queueName);
            }
            return queueHolder;
        } catch (Exception e) {
            throw new QueueException("QueueFactory get queue exception. " + e);
        }
    }


}
